<template>
  <div class="group-msg" v-if="user.show">
    <div class="chat-top">
      <span class="group-name">小二蚁巢工作群(5)</span>
      <span class="group-tool" @click="openGroupTool">
        <img :src="require('@/assets/shenglv.png')">
      </span>
    </div>
    <el-scrollbar ref="chat-box" class="chat-middle">
      <div class="chat-list" v-for="(item,index) in chatMsg">
        <div :class="item.sendPerson !== user.userId ?'chat-list-left':'chat-list-right'">
          <img :src="item.avatar" class="list-img"/>
          <div :class="item.sendPerson !== user.userId ? 'left-msg' : 'right-msg'">
            <span class="msg-content" v-if="item.fileType===0">
              {{ item.msg }}
            </span>
            <span class="msg-img" v-else>
              <img :src=item.msg alt="#">
            </span>
          </div>
        </div>
      </div>
    </el-scrollbar>

    <div class="chat-boom">
      <div class="chat-tool">
        <el-popover placement="top-start" width="250" trigger="click" class="emoBox">
          <div class="emotionList">
            <a href="javascript:void(0);" @click="getEmoji(index)" v-for="(item,index) in faceList" :key="index"
               class="emotionItem">{{ item }}</a>
          </div>
          <span class="emotionSelect" slot="reference">
             <img :src="require('@/assets/emoji.png')" alt="表情库">
          </span>
        </el-popover>

        <el-popover
            placement="top-start"
            width="250"
            trigger="click"
        >
          <div class="photo-top">
            <el-image
                v-for="(item,index) in photoList" :key="index" @click="concatPhoto(item)"
                :src="item.photo"
                fit="cover"
            >
            </el-image>
            <span class="photo-upload">
             <el-upload
                 class="avatar-uploader"
                 action=""
                 :show-file-list="false"
                 :http-request="uploadPhotoMethod">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            </span>
          </div>
          <span class="tool-select" slot="reference">
             <img :src="require('@/assets/photo.png')" alt="上传图片">
          </span>
        </el-popover>
      </div>


      <el-input class="textarea" resize="none" type="textarea" :rows="7" placeholder="ENTER 快捷发送" v-model.trim="msg"
                ref="msg">
      </el-input>

      <el-button type="primary" :disabled="this.msg ===''" @click="send" plain @keyup.enter="keyDown(e)"
                 class="send-button">发送(S)
      </el-button>
    </div>
  </div>
</template>

<script>
import {groupChatMsgList} from '@/api/group/index'
import {sendGroupMsg} from '@/api/chat/index'
import emoji from '@/assets/emoji.json'
import {upload} from "@/utils/upload";
import {photoAdd, getPhotoList} from '@/api/tool/index'

export default {
  name: "index",
  computed: {
    monitor() {
      return this.$store.state.groupMsg
    }
  },
  props: {
    obj: {
      require: true,
      default() {
        return {};
      },
      type: Object
    },
    closeGroupProp: {
      require: true,
      default() {
        return false;
      },
      type: Boolean
    }
  },
  data() {
    return {
      msg: '',
      chatMsg: [],
      user: {
        receiverPerson: '',
        userId: '',
        show: false
      },
      faceList: [],
      photoList: [],
      showGroupTool: false
    }
  },
  methods: {
    //发送消息
    send() {
      let sendObj = {
        receiverPerson: this.user.receiverPerson,
        msg: this.msg,
        msgType: 1,
        fileType: 0
      }
      sendGroupMsg(sendObj).then(res => {
        this.groupChatMsgListMethod()
      }).catch(error => {

      })
      this.msg = ''
    },
    //查询群组消息列表
    groupChatMsgListMethod() {
      groupChatMsgList(this.user.receiverPerson).then(res => {
        if (res.code === 200) {
          this.chatMsg = res.data
        }
        this.contentMiddle()
      }).catch(error => {

      })
    },
    // 回车键快捷发送
    keyDown(e) {
      if ((e.keyCode === 13 || e.keyCode === 100) && this.msg !== '') {
        this.send()
      }
    },
    //聊天内容置于最底部
    contentMiddle() {
      this.$nextTick(() => {
        let chatBox = this.$refs['chat-box']
        chatBox.wrap.scrollTop = chatBox.wrap.scrollHeight
      })
    },
    //获取表情
    getEmoji(index) {
      let msg = this.$refs['msg']
      let str = this.faceList[index]
      this.msg = msg._props['value'].concat(str)
    },
    //拼接图片信息
    concatPhoto(model) {
      //直接发送消息
      let sendObj = {
        receiverPerson: this.user.receiverPerson,
        msg: model.photo,
        msgType: 1,
        fileType: 1
      }
      sendGroupMsg(sendObj).then(res => {
        this.groupChatMsgListMethod()
      }).catch(error => {

      })
      this.msg = ''
    },
    //上传图片
    uploadPhotoMethod(file) {
      upload(file.file).then(res => {
        if (res !== null) {
          photoAdd({"photo": res}).then(res => {
            if (res.code === 200) {
              this.$message.success("上传表情包成功")
              //刷新表情包列表
              this.refreshPhoto()
            }
          }).catch(error => {

          })
        }
      }).catch(res => {

      })
    },
    //刷新表情包列表信息
    refreshPhoto() {
      getPhotoList().then(res => {
        if (res.code === 200) {
          this.photoList = res.data
        }
      }).catch(error => {

      })
    },
    //打开群聊工具栏
    openGroupTool() {
      this.showGroupTool = true
      this.$emit('showTool', {
        flag: this.showGroupTool,
        height: document.getElementsByClassName("group-msg")[0].clientHeight
      })
    }
  },
  watch: {
    obj(newValue) {
      this.user = Object.assign(newValue)
      this.groupChatMsgListMethod()
    },
    //监听群组的数据
    monitor() {
      // 必须处于聊天的页面才进行刷新
      if (this.$route.path === "/group" && this.$store.state.groupMsg.code === 10006 && this.$store.state.groupMsg.userId !== sessionStorage.getItem("userId")) {
        this.groupChatMsgListMethod()
        this.contentMiddle()
      }
    },
    closeGroupProp(newValue) {
      this.showGroupTool = newValue
    }
  },
  mounted() {
    //绑定键盘按下事件
    window.addEventListener("keydown", this.keyDown);
    //表情数据
    for (let i in emoji) {//读取json文件保存数据给数组
      this.faceList.push(emoji[i].char);
    }
    //表情包数据
    this.refreshPhoto()
  },
  destroyed() {
    //销毁键盘按下事件
    window.removeEventListener("keydown", this.keyDown, false)
    window.speechSynthesis.cancel()
  }
}
</script>
<style lang="scss">
/* el-popover是和app同级的，所以scoped的局部属性设置无效 */
/* 需要设置全局style */
.el-popover {
  height: 150px;
  width: 450px;
  overflow: scroll;
  overflow-x: auto;
}
</style>

<style scoped lang="scss">

.group-msg {
  height: 100%;
  display: flex;
  background: rgb(247, 247, 247);
  flex-direction: column;
  justify-content: space-between;
}

.chat-list {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-list-left {
  padding: 20px;
  display: flex;
  flex-direction: row;
}

.list-img {
  width: 40px;
  height: 40px;
  border-radius: 5px;
}

.left-msg {
  margin-left: 5px;
  background: #ffffff;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
}

.chat-list-right {
  padding: 20px;
  display: flex;
  flex-direction: row-reverse;
}

.right-msg {
  margin-right: 5px;
  font-size: 15px;
  border-radius: 6px;
  max-width: 200px;
  word-wrap: break-word;
  background-color: #4ccb69;
}

.chat-top {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  justify-items: center;
  align-items: center;
  grid-template-areas: 'a b c';
}

.chat-middle {
  flex: 6;
  overflow: scroll;
}

.chat-boom {
  flex: 3;
  position: relative;
}

.send-button {
  float: right;
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.msg-content {
  display: block;
  padding: 10px 10px 10px 10px;
}


.emotionSelect:hover {
  background-color: white;
}

.emotionList {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
}

.emotionItem {
  width: 10%;
  font-size: 20px;
  text-align: center;
}

/*包含以下四种的链接*/
.emotionItem {
  text-decoration: none;
}

/*正常的未被访问过的链接*/
.emotionItem:link {
  text-decoration: none;
}

/*已经访问过的链接*/
.emotionItem:visited {
  text-decoration: none;
}

/*鼠标划过(停留)的链接*/
.emotionItem:hover {
  text-decoration: none;
}

/* 正在点击的链接*/
.emotionItem:active {
  text-decoration: none;
}

.chat-tool {
  width: 100%;
  height: 40px;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  grid-template-areas: 'a b';
  justify-items: center;
  align-items: center;
  background-color: #d9d9d9;
}

.emotionSelect {
  display: block;
  width: 20px;
  height: 20px;
  grid-area: a;
  border-radius: 10px;

  img {
    width: 100%;
    height: 100%;
    background-size: 100%;
  }
}

//发送图片工具栏
.tool-select {
  display: block;
  width: 20px;
  height: 20px;
  grid-area: b;
  border-radius: 10px;

  img {
    width: 100%;
    height: 100%;
    background-size: 100%;
  }
}

.photo-top {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  align-items: center;
  row-gap: 20px;
  text-align: center;

  .el-image {
    width: 40px;
    height: 40px;
    display: block;
    margin: 0 auto;
  }

  .photo-upload {
    width: 40px;
    height: 40px;
    display: flex;
    margin: 0 auto;
    grid-area: 1/1;
    align-items: center;

    .avatar-uploader {
      flex: 1;
    }
  }
}

.msg-img {
  display: block;
  width: 200px;
  height: 200px;

  img {
    width: 100%;
    height: 100%;
  }
}

.group-name {
  display: block;
  font-size: 17px;
  font-weight: 500;
  grid-area: a;
}

.group-tool {
  display: block;
  grid-area: c;
  width: 20px;
  height: 20px;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>